package com.h3c.nem.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.h3c.nem.dto.mapstruct.NewWorkerDTO;
import com.h3c.nem.entity.*;
import com.h3c.nem.enums.CareInfoType;
import com.h3c.nem.service.ITbWorkerCareService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * 新员工关怀service
 *
 * @author z22968
 * @date 2022/6/8 15:17
 */
@Slf4j
@Service
public class TbWorkerCareServiceImpl implements ITbWorkerCareService {
    @Resource
    TbOfferWorkerServiceImpl tbOfferWorkerService;
    @Resource
    SdDeptServiceImpl sdDeptService;
    @Resource
    SdAllWorkerServiceImpl sdAllWorkerService;
    @Resource
    TbCareNoticeSettingServiceImpl tbCareNoticeSettingService;

    @Override
    public List<TbCareInfo> getNoticeList(NewWorkerDTO worker) {
        String empCode = worker.getWorkerId();
        Assert.hasText(empCode, "工号不能为空");
        TbOfferWorker offerWorker = tbOfferWorkerService.getById(empCode);
        List<TbCareInfo> result = new ArrayList<>();
        String inType = offerWorker.getInType();
        if (inType.equals("社会招聘")) {
            // 获取短周期推送人数
            TbCareNoticeSetting socialShortSetting = tbCareNoticeSettingService.selectOne(TbCareNoticeSetting.SettingType.PEOPLE_NUM, CareInfoType.SOCIAL_SHORT.getName());
            result = getShortCycle(worker, socialShortSetting.getValue());

            // 获取长周期推送人数
            TbCareNoticeSetting socialLongSetting = tbCareNoticeSettingService.selectOne(TbCareNoticeSetting.SettingType.PEOPLE_NUM, CareInfoType.SOCIAL_LONG.getName());
            result = getLongCycle(worker, socialLongSetting.getValue(), result);
        } else {

        }
        return result;
    }

    /**
     * 获取社招短周期推送人员
     *
     * @param worker 新员工信息
     * @param limit  最大人数
     * @return java.util.List<com.h3c.nem.dto.mapstruct.NewWorkerDTO>
     * @author z22968
     * @date 2022-06-08 17:45
     */
    public List<TbCareInfo> getShortCycle(NewWorkerDTO worker, Integer limit) {
        List<TbCareInfo> result = new ArrayList<>();
        Integer dept3id = worker.getDept3id();
        Assert.notNull(dept3id, "该用户无三级部门 工号：" + worker.getWorkerId());
        Integer dept4id = worker.getDept4id();
        // 获取三四级领导
        LambdaQueryWrapper<SdDept> sdDeptLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sdDeptLambdaQueryWrapper.eq(SdDept::getDeptId, dept3id);
        if (dept4id != null) {
            sdDeptLambdaQueryWrapper.or().eq(SdDept::getDeptId, dept4id);
        }
        List<Map<String, Object>> idMap = sdDeptService.getBaseMapper().selectEmpCodes(sdDeptLambdaQueryWrapper);
        if (!CollectionUtils.isEmpty(idMap)) {
            result = JSONArray.parseArray(JSONArray.toJSONString(idMap), TbCareInfo.class);
        }
        // 人数不够
        if (result.size() < limit) {
            QueryWrapper<SdAllWorker> sdAllWorkerQueryWrapper = new QueryWrapper<>();
            sdAllWorkerQueryWrapper.eq("direct_dept_id", worker.getDirectDeptId());
            getWorkerList(result, null, limit, sdAllWorkerQueryWrapper);
        }
        if (result.size() > limit) {
            result.subList(0, limit - 1);
        }
        for (TbCareInfo careInfo : result) {
            careInfo.setNewWorkerId(worker.getWorkerId());
            careInfo.setType(CareInfoType.SOCIAL_SHORT);
        }
        return result;
    }

    public List<TbCareInfo> getLongCycle(NewWorkerDTO worker, Integer limit, List<TbCareInfo> shortList) {
        List<TbCareInfo> result = new ArrayList<>();
        List<String> ids = shortList.stream().map(TbCareInfo::getOldWorkerId).collect(Collectors.toList());
        QueryWrapper<SdAllWorker> sdAllWorkerQueryWrapper = new QueryWrapper<>();
        Integer dept3id = worker.getDept3id();
        Integer dept4id = worker.getDept4id();
        // 当前在四级部门且人数不够时，获取三级部门的人
        if (dept4id != null) {
            // 获取该四级部门人数
            sdAllWorkerQueryWrapper.eq("direct_dept_id", worker.getDirectDeptId());
            int dept4Num = sdAllWorkerService.count(sdAllWorkerQueryWrapper);
            sdAllWorkerQueryWrapper.clear();
            // 人数不够使用3级部门
            if (limit > (dept4Num - ids.size())) {
                sdAllWorkerQueryWrapper.eq("direct_dept_id", dept3id);
                getWorkerList(result, ids, limit, sdAllWorkerQueryWrapper);
            } else {
                // 人数够直接用四级部门
                sdAllWorkerQueryWrapper.eq("direct_dept_id", dept4id);
                getWorkerList(result, ids, limit, sdAllWorkerQueryWrapper);
            }
        } else {
//            // 在三级部门直接使用
//            sdAllWorkerQueryWrapper.eq("direct_dept_id", dept3id);
//            getWorkerList(result, limit, sdAllWorkerQueryWrapper);
        }

        // TODO 三年以内同一学校跳过
        // 人数不够,获取同乡
        if (result.size() < limit) {
            sdAllWorkerQueryWrapper.eq("certificate_no_top_six", worker.getCertificateNoTopSix());
            getWorkerList(result, ids, limit, sdAllWorkerQueryWrapper);
        }
        // 人数不够,获取同工作旅行地
        if (result.size() < limit) {
            sdAllWorkerQueryWrapper.eq("work_city", worker.getWorkCity());
            getWorkerList(result, ids, limit, sdAllWorkerQueryWrapper);
        }
        // TODO 办公区域跳过
        if (result.size() > limit) {
            result.subList(0, limit - 1);
        }
        for (TbCareInfo careInfo : result) {
            careInfo.setNewWorkerId(worker.getWorkerId());
            careInfo.setType(CareInfoType.SOCIAL_LONG);
        }
        return result;
    }

    public void getWorkerList(List<TbCareInfo> curList, List<String> excludeIds, Integer limit, QueryWrapper<SdAllWorker> sdAllWorkerQueryWrapper) {
        List<String> ids = curList.stream().map(TbCareInfo::getOldWorkerId).collect(Collectors.toList());
        int limitNum = limit - curList.size();
        if (!CollectionUtils.isEmpty(excludeIds)) {
            ids.addAll(excludeIds);
        }
        if (!CollectionUtils.isEmpty(ids)) {
            sdAllWorkerQueryWrapper.notIn("worker_id", ids);
        }
        Integer count = sdAllWorkerService.getBaseMapper().selectCount(sdAllWorkerQueryWrapper);
        // 如果sql查询总数比需要的数量多，则随机获取
        int randomStart = 0;
        if (count > limitNum) {
            int start = count - limitNum;
            Random random = new Random();
            // 随机从0-start中生成一个数字
            randomStart = random.nextInt(start + 1);
        }
        sdAllWorkerQueryWrapper.select("worker_id as old_worker_id").last("limit " + randomStart + "," + limitNum);
        List<Map<String, Object>> maps = sdAllWorkerService.getBaseMapper().selectMaps(sdAllWorkerQueryWrapper);
        List<TbCareInfo> deptWorkers = JSONArray.parseArray(JSONArray.toJSONString(maps), TbCareInfo.class);
        curList.addAll(deptWorkers);
        sdAllWorkerQueryWrapper.clear();
    }
}
